/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import models.Course;
import models.User;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;
import service.CourseDao;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author kjeld
 */
@WebServlet(name = "TutorLiveStreamController", urlPatterns = {"/tutorlivestream"})
public class TutorLiveStreamController extends HttpServlet {

    private String filename;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String address = "/tutorlivestream.jsp";
        long userID = 0;
        boolean tutor = false;
        boolean admin = false;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("status")) {
                if (cookie.getValue().equals("Tutor")) {
                    tutor = true;
                } else if (cookie.getValue().equals("Admin")) {
                    tutor = true;
                    admin = true;
                }
            } else if (cookie.getName().equals("userID")) {
                userID = Long.parseLong(cookie.getValue());
            }
        }
        if (tutor == true) {
            HttpSession session = request.getSession(true);
            HibernateUtil HU = new HibernateUtil();
            Session sessie = HU.openSession();
            if(request.getParameter("courseID") != null){
            try {
                //stuk om de deelnemende studenten van de door de docent gekozen cursus te showen
                CourseDao cd = new CourseDao(sessie);
                long d = Long.parseLong(request.getParameter("courseID"));//dit moet dynamsich worden
                Course course = cd.get(d);
                if (course != null) {
                    String courseName = course.getName();
                    courseName = courseName.toLowerCase();
                    char[] charArray = courseName.toCharArray();
                    String streamName = "";
                    for(int i = 0; i < charArray.length; i++){
                        char c = charArray[i];
                        if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')){
                            streamName += c;
                        }
                    }
                    session.setAttribute("streamname", streamName);
                    filename = streamName;
                    session.setAttribute("courseID", request.getParameter("courseID"));
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
            }
            else {
                session.setAttribute("courseID",null);
                CourseDao cd = new CourseDao(sessie);
                UserDao udao = new UserDao(sessie);
                //User user = udao.get(Long.parseLong(teacherArray.nextToken()));
                //user.addCourse(course);
                User user = udao.get(userID);
                Set<Course> courses = user.getCourses();
                session.setAttribute("courses", courses);
            }
            session.setAttribute("admin",admin);
            
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        } else {
            response.sendRedirect("/");
        }
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            IOException, ServletException {
        //filePath = getServletContext().getRealPath("/") + "files/";
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
 
                    if (!item.isFormField()) {
                        String fileName = item.getName();
 
                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/files/dcfiles/" + filename);
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher("tutorlivestream.jsp");
        dispatcher.forward(request, response);
    }
}
